#include <maya/MStringArray.h>
#include "ColladaExporterOptions.h"

// Unescapes an option string.
void OptionStringUnescape(const char* pSource, int iFrom, int iTo, char* pDestination)
{
	for (int i = iFrom; i <= iTo; i++)
	{
		if (pSource[i] == '\\')
		{
			i++;
			if (i <= iTo)
			{
				*pDestination = pSource[i];
				pDestination++;
			}
		}
		else
		{
			*pDestination = pSource[i];
			pDestination++;
		}
	}
	*pDestination = '\x0';
}

// Returns the index of the next occurrence of specified character in specified string.
int NextIndexOf(const char* pSource, int iLength, char cLookFor, int iStartIndex)
{
	for (int i = iStartIndex; i < iLength; i++)
	{
		if (pSource[i] == '\\') i++;
		else if (pSource[i] == cLookFor) return i;
	}
	return -1;
}

ColladaExporterOptions::ColladaExporterOptions(const MString& optionsString)
{
	int len = (int)optionsString.length();
	const char* options = optionsString.asChar();
	int pos = 0;
	// Skip the first character if its a ';' (don't know why we get this character sometimes).
	if (len > 0 && options[0] == ';') pos++;
	while (pos < len)
	{
		// Find the next index of '='.
		int nextEqual = NextIndexOf(options, len, '=', pos);
		
		// If we found one...
		if (nextEqual != -1)
		{
			// Obtain the option name.
			char optionName[512]; // TODO: possible buffer overrun.
			OptionStringUnescape(options, pos, nextEqual - 1, optionName);

			// Skip it.
			pos = nextEqual + 1;

			// Find the next index of ';'.
			int nextSemicolon = NextIndexOf(options, len, ';', pos);

			// If we found one...
			if (nextSemicolon != -1)
			{
				// Copy to obtain value.
				char optionValue[512]; // TODO: possible buffer overrun.
				OptionStringUnescape(options, pos, nextSemicolon - 1, optionValue);

				// Skip it.
				pos = nextSemicolon + 1;

				// Load option.
				SetOption(MString(optionName), MString(optionValue));
			}
			else break;
		}
		else break;
	}
}

